<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>测试页面</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .btn {
      width: 200px;
      height: 100px;
      border-radius: 20px;
    }

    #btn1 {
      background-color: green;
    }

    #btn2 {
      background-color: red;
    }
  </style>

  <!-- <script type="module" src="https://cdn.bootcdn.net/ajax/libs/mqtt/5.8.1/mqtt.js"></script> -->
  <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>

</head>

<body>
  <button class="btn" id="btn1">开灯按钮</button>
  <button class="btn" id="btn2">关灯按钮</button>
  <br>
  <br>
  <hr>
  <h2>消息队列温度展示： </h2>
  <div class="msg"></div>


  <script>

    let btn1Node = document.querySelector('#btn1');
    let btn2Node = document.querySelector('#btn2');
    let listNode = document.querySelector('.list');
    let msgNode = document.querySelector('.msg');

    const client = mqtt.connect('ws://192.168.21.57:1883'); // 使用 MQTT.js 连接 MQTT服务器

    // 绑定监听
    client.on('connect', () => {
      // 订阅消息队列
      client.subscribe('gateway_to_remote', (err) => {
        if (!err) {
          console.log('Subscribed to gateway_to_remote');
        }

      });

    });

    function hexToString(hex) {
      var str = '';
      for (var i = 0; i < hex.length; i += 2) {
        str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
      }
      return str;
    }

    // 接收来自消息队列1的数据
    client.on('message', (topic, message) => {
      console.log(JSON.parse(message.toString()));
      let testData = JSON.parse(message.toString());
      console.log('----', testData);
      msgNode.textContent = "当前温度：" + hexToString(testData.msg) + "度";
    });

    // 给指定的消息队列发送数据
    function sendMessage(message, queueName) {
      // 消息队列名字可以随时改： test/1, message:发送的消息数据
      client.publish(queueName, message);
      console.log(`发送消息给${queueName}队列`);
    }

    /* 开灯 */
    btn1Node.addEventListener('click', () => {
      sendMessage(JSON.stringify({
        'conn_type': 1,
        'id': '0088',
        'msg': '31'
      }), 'remote_to_gateway')
    })
    /* 关灯 */
    btn2Node.addEventListener('click', () => {
      sendMessage(JSON.stringify({
        'conn_type': 1,
        'id': '0088',
        'msg': '30'
      }), 'remote_to_gateway')
    })

  </script>
</body>

</html>